import sys
from collections import deque
toks = (tok for tok in sys.stdin.read().split())
N = int(next(toks))
X = int(next(toks))-1
adj = [[] for _ in range(N)]
for _ in range(N-1):
v1 = int(next(toks))-1
v2 = int(next(toks))-1
adj[v1].append(v2)
adj[v2].append(v1)
def find_dsts(st):
dsts = [None for _ in range(N)]
bfs_q = deque()
bfs_q.append(st)
dsts[st] = 0
while len(bfs_q) > 0:
cur_v = bfs_q.popleft()
for next_v in adj[cur_v]:
if dsts[next_v] == None:
dsts[next_v] = dsts[cur_v]+1
bfs_q.append(next_v)
return dsts
dsts_from_alice = find_dsts(0)
dsts_from_bob = find_dsts(X)
answer = 2*dsts_from_alice[X]
vis = [False for _ in range(N)]
bfs_q = deque()
bfs_q.append(X)
vis[X] = True
while len(bfs_q) > 0:
cur_v = bfs_q.popleft()
for next_v in adj[cur_v]:
if vis[next_v]: continue
if dsts_from_alice[next_v] < dsts_from_bob[next_v]:
answer = max(answer, 2*dsts_from_bob[next_v]-1)
elif dsts_from_alice[next_v] == dsts_from_bob[next_v]:
answer = max(answer, 2*dsts_from_bob[next_v])
else:
answer = max(answer, 2*dsts_from_alice[next_v])
vis[next_v] = True
bfs_q.append(next_v)
print(answer)
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define MAX 200005
int he[MAX],ne[MAX*2],etop=1,x,n,ans,d[MAX],d1[MAX];
bool vis[MAX];
struct edge
{
int to,cost;
edge(){}
edge(int v,int c)
{
to=v;
cost=c;
}
}ed[MAX*2];
void dfs(int x)
{
vis[x]=1;
for(int i=he[x];i;i=ne[i])
{
edge& e=ed[i];
if(vis[e.to])
continue;
vis[e.to]=1;
d[e.to]=d[x]+e.cost;
dfs(e.to);
}
}
void dfs1(int x)
{
vis[x]=1;
for(int i=he[x];i;i=ne[i])
{
edge& e=ed[i];
if(vis[e.to])
continue;
vis[e.to]=1;
d1[e.to]=d1[x]+e.cost;
dfs1(e.to);
}
}
int main()
{
scanf("%d%d",&n,&x);
for(int i=1;i<=n-1;i++)
{
int u,v,c;
scanf("%d%d",&u,&v);
ed[etop]=edge(v,1);
ne[etop]=he[u];
he[u]=etop++;
ed[etop]=edge(u,1);
ne[etop]=he[v];
he[v]=etop++;
}
dfs(x);
memset(vis,0,sizeof(vis));
dfs1(1);
ans=0;
for(int i=1;i<=n;i++)
{
//cout<<"d["<<i<<"]"<<d[i]<<" d1["<<i<<"]"<<d1[i]<<endl;
if(d[i]>=d1[i])
continue;
ans=max(ans,d1[i]);
}
cout<<ans*2<<endl;
return 0;
}
2B - The least round way | 1324A - Yet Another Tetris Problem |
246B - Increase and Decrease | 22E - Scheme |
1566A - Median Maximization | 1278A - Shuffle Hashing |
1666F - Fancy Stack | 1354A - Alarm Clock |
1543B - Customising the Track | 1337A - Ichihime and Triangle |
1366A - Shovels and Swords | 919A - Supermarket |
630C - Lucky Numbers | 1208B - Uniqueness |
1384A - Common Prefixes | 371A - K-Periodic Array |
1542A - Odd Set | 1567B - MEXor Mixup |
669A - Little Artem and Presents | 691B - s-palindrome |
851A - Arpa and a research in Mexican wave | 811A - Vladik and Courtesy |
1006B - Polycarp's Practice | 1422A - Fence |
21D - Traveling Graph | 1559B - Mocha and Red and Blue |
1579C - Ticks | 268B - Buttons |
898A - Rounding | 1372B - Omkar and Last Class of Math |